package ac.il.technion.c236369.hw4.core.protocol;

import java.io.IOException;

import org.apache.http.HttpException;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.log4j.Logger;

import ac.il.technion.c236369.hw4.core.entity.EntityTemplate;
import ac.il.technion.c236369.hw4.core.producers.InternalErrorContentProducer;

/**
 * @author Artem Barger, Maxim Aizenshtein
 * 
 * Class to handle and send internal error report to client
 *
 */
public class InternalErrorReport {

	private DefaultHttpServerConnection connection = null;
	private Logger log = Logger.getLogger( InternalErrorReport.class);
	
	public InternalErrorReport( DefaultHttpServerConnection connection) {
		this.connection = connection;
		log.info( "About to send internal error report to: <" + connection.getRemoteAddress( ) + ">");
	}
	
	/**
	 * Send an internal error notification report to client
	 * 
	 * @throws IOException
	 */
	public void sendErrorReport( ) throws IOException {
		BasicStatusLine statusLine = new BasicStatusLine( HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Could not serve connection");
		BasicHttpResponse response = new BasicHttpResponse( statusLine);
		EntityTemplate body = new EntityTemplate( new InternalErrorContentProducer( ));
		response.setEntity(body);
		try {
			BasicHttpContext context = new BasicHttpContext();
			new ResponseDate().process(response, context);
			new ResponseServer().process(response, context);
			new ResponseContent().process(response, context);
			response.addHeader( "Connection", "close");
			connection.sendResponseHeader(response);
			connection.sendResponseEntity(response);
		} catch (HttpException e) {
			log.error( e);
		}
		connection.flush();
		log.info( "Internal error report has been sent to client: <" + connection.getRemoteAddress( ) + ">");
	}
}
